<?php

require 'sql.php';
require 'sanitize.php';
require 'vaildateLogin.php';

$conn = mysql_connect($server, $user, $passwd) or die('Could not connect to SQL server ' .mysql_error());
mysql_select_db($database, $conn) or die('Could not connect to given database' .mysql_error());
$_SREQUEST = sanitize($_REQUEST);
$accesstoken = 37;
if (isset($_SREQUEST['method'])) {
	// If the user wants to login
	if($_SREQUEST['method'] == 'login' && isset($_SREQUEST['username']) && isset($_SREQUEST['password'])){
		$password = md5($_SREQUEST['password']);
		$username = $_SREQUEST['username'];
		// Check if the users username and login match with the db
		$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
		$result = mysql_fetch_row($query);
		if($result == 0){
			// User login failed
			header("HTTP/1.0 401 UNAUTHORIZED");
		}else{
			$id = $result['0'];
			//$accesstoken = 37; // should be something more randon :)
			$accesstoken = md5(md5($id) + md5(time()) + $result['2']);
			// Update the accesstoken in the db
			$query = mysql_query("UPDATE users SET accesstoken='$accesstoken' WHERE username='$username' AND id='$id'");
			$loggedin = true;
			// Return json with some data needed for the users session
			$jsonreturn = array(array ("loggedin"  => $loggedin, "id" => $id, "accesstoken" => $accesstoken, "username" => $username));
			print json_encode($jsonreturn);
		}

		// If the user wants to logout
	}elseif($_SREQUEST['method']=='logout' && isset($_SREQUEST['id']) && isset($_SREQUEST['accesstoken'])){
		$accesstoken = $_SREQUEST['accesstoken'];
		$id = $_SREQUEST['id'];
		// Reset the accesstoken in db
		$query = mysql_query("UPDATE users SET accesstoken='' WHERE id='$id' AND accesstoken='$accesstoken'");
		if(mysql_affected_rows() == 0){
			// User is not authorized
			header("HTTP/1.0 401 UNAUTHORIZED");
		}else{
			header("HTTP/1.0 200 OK");
		}
		mysql_close();
	}elseif($_SREQUEST['method']=='validate' && isset($_SREQUEST['id']) && isset($_SREQUEST['accesstoken'])){
		$accesstoken = $_SREQUEST['accesstoken'];
		$id = $_SREQUEST['id'];
		$valid = validateLogin($id, $accesstoken);
		print json_encode(array(array("valid" => $valid)));
	}
}else{
	header("HTTP/1.0 404 NOT FOUND");
}
?>
